#include <amxmodx>
#include <fakemeta>
#include <hamsandwich>
#include <orpheu>
#include <orpheu_memory>

#define GetPlayerByClientStruct(%0)     ( ( %0 - g_client_t_address ) / 20200 + 1 )

new g_top_client
new g_client_t_address
new g_player_voice_status[ 32 ]

new g_fwdVoiceRecordOn
new g_fwdVoiceRecordOff

public plugin_init()
{
    register_forward( FM_Voice_SetClientListening, "fwd_Voice_SetClientListening" )
    OrpheuRegisterHook( OrpheuGetFunction( "SV_ParseVoiceData" ), "SV_ParseVoiceData" )
    RegisterHam( Ham_Spawn, "player", "hamPlayerSpawn" )

    g_fwdVoiceRecordOn = CreateMultiForward( "client_voicerecord_on", ET_IGNORE, FP_CELL )
    g_fwdVoiceRecordOff = CreateMultiForward( "client_voicerecord_off", ET_IGNORE, FP_CELL )

    new svs = OrpheuMemoryGet( "svs_ptr" )

    g_client_t_address = OrpheuMemoryGetAtAddress( svs + 4, "engineInt" )
    arrayset( g_player_voice_status, 0, 32 )
    g_top_client = 0
}

public SV_ParseVoiceData( info )
{
    // Flag user as it's using voicerecord
    new player = GetPlayerByClientStruct( info )
    g_player_voice_status[ player - 1 ] = 1

}

public hamPlayerSpawn( id )
{
    set_top_client()
    g_player_voice_status[ id - 1 ] = 0
}

public fwd_Voice_SetClientListening( receiver, sender, bool:listen )
{
    new result
    // Detect +voicerecord
    if( receiver == 1 && g_player_voice_status[ sender - 1 ] )
    {
        ExecuteForward( g_fwdVoiceRecordOn, result, sender )
    }

    // Detect -voicerecord
    if( receiver == g_top_client && g_player_voice_status[ sender - 1 ] )
    {
        ExecuteForward( g_fwdVoiceRecordOff, result, sender )
        g_player_voice_status[ sender - 1 ] = 0
    }

    return FMRES_IGNORED
}

public client_disconnect( id )
{
    set_top_client()
    g_player_voice_status[ id - 1 ] = 0
}

stock set_top_client()
{
    new players[ 32 ], num

    get_players( players, num )

    for( num--; num >= 0; num-- )
    {
        if( players[ num ] > g_top_client )
          g_top_client = players[ num ]
    }
}  